<#
#=======================================================================================
# Name: InstallSCCMSite.ps1
# Version: 0.2
# Author: Raphael Perez - raphael@rflsystems.co.uk
# Date: 10/01/2013
# Comment: This script will perform the Configuration Manager 2012 SP1 Installation and initial configuration
# 
# Updates:
#        0.1 - Raphael Perez - 05/10/2012 - Initial Script
#        0.2 - Raphael Perez - 10/01/2013
#                      - Changed the Folder Structure for Devices and Users
#                      - Removed Folder and Collections (Now it is on CreateProjectStructure.ps1)
#                      - Added configuration of the maintenance task "Delete Aged Replication Summary Data" to run every 60 days instead 90
#                      - Added try/finally
#                      - Fixed running discovery issue
#                      - Added option to run only on powershell v3
#                      - Changed folder for SCCM pre-req
#					   - Added Support for WS2012
#                      - removed option to show the password when writting to log file
#                      - validation replication (sms_site.mode) instead of waiting 300+900 seconds.
#                      - added question about the sccmadmin group
#
# Usage:
#		 Option 1: powershell.exe -ExecutionPolicy Bypass .\InstallSCCMSite.ps1 [Parameters]
#        Option 2: Open Powershell and execute .\InstallSCCMSite.ps1 [Parameters]
#
# Parameters: (All parameters are optional, if you do not use, script will ask you to provide the information)
#        siteinstallationtype - 1,2,3,4 - Site installation type (1=central, 2=primary standard, 3=primary child, 4=secondary) 
#        sdkServer - server that will be the sdk server
#        sitecode - sitecode
#        sitename - site name
#        ParentSiteServer - used when siteinstallationtype = 3 or 4 - parent site server (fqdn)
#        localdatabase - y/n - Use Y if the sql server will be local
#        sqlserver - used when localdatabase = 'n'
#        changeDatabase - y/n - change the inicial number of DB files and size
#        InitialSize - used when changeDatabase = 'y' - inicial database size in GB
#        NumberOfFiles - used when changeDatabase = 'y' - number of database files
#        useclientpush - y/n - if you want to set up the client push account
#        ClientPushAccount - used when useclientpush = 'y' - username
#        ClientPushAccountPassword - used when useclientpush = 'y' - passowrd
#        usenetworkaccessaccount - y/n - if you want to set up the network access account
#        NetworkAccessAccount - used when usenetworkaccessaccount = 'y' - username
#        NetworkAccessAccountPassword - used when usenetworkaccessaccount = 'y' - password
#        createServerBoundary - y/n - if you want to create a boundary range (it uses the server IP address/network mask to perform this)
#        forestdiscovery - y/n - enable forest discovery
#        systemdiscovery - y/n - enable system discovery (for the DOMAIN)
#        userdiscovery - y/n - enable user discovery (for the DOMAIN)
#        groupdiscovery - y/n - enable group discovery (for the DOMAIN)
#        ParentSiteCode - used when siteinstallationtype = 4
#        SecondaryServerNetbiosName - used when siteinstallationtype = 4
#        sccmadmingroup - add this group to as full admin on sccm infrastructure
#
# Examples:
#        ./InstallSCCMSite -siteinstallationtype '2' -sdkServer 'sccm01.mylab.com' -sitecode '001' -sitename '001 Site' -localdatabase 'y' -changeDatabase 'y' -InitialSize 5 -NumberOfFiles 1 -useclientpush 'y' -ClientPushAccount 'sccmpush' -ClientPushAccountPassword 'Pa$$w0rd' -usenetworkaccessaccount 'y' -NetworkAccessAccount 'sccmna' -NetworkAccessAccountPassword 'Pa$$w0rd' -createServerBoundary 'y' -forestdiscovery 'n' -systemdiscovery 'n' -userdiscovery 'n' -groupdiscovery 'n' -ParentSiteCode '' -SecondaryServerNetbiosName ''
#        - install primary site stand alone, the sdk server will be sccm01.mylab.com, sitecode 001, site name 001 Site, using local database
#        - the initial database size will be 5gb and it will be only 1 file, client push and network account will be set up
#        - will create a boundary (and boundary group) as well as collections and folders (device and user collections)
#        - will not enable any discovery
#=======================================================================================
#>
PARAM(
    $siteinstallationtype = '',
    $sdkServer = '',
    $sitecode = '',
    $sitename = '',
    $ParentSiteServer = '',
    $localdatabase = '',
    $sqlserver = '',
    $changeDatabase = '',
    $InitialSize,
    $NumberOfFiles,
    $useclientpush = '',
    $ClientPushAccount = '',
    $ClientPushAccountPassword = '',
    $usenetworkaccessaccount = '',
    $NetworkAccessAccount = '',
    $NetworkAccessAccountPassword = '',
    $createServerBoundary = '',
    $forestdiscovery = '',
    $systemdiscovery = '',
    $userdiscovery = '',
    $groupdiscovery = '',
    $ParentSiteCode = '',
    $SecondaryServerNetbiosName = ''
)
try
{
    $ErrorActionPreference = "Stop"
    $maxretry = 5
    $MediaFolder = $MediaFolder = (Get-Item (Get-Location).Path).Parent.FullName
    if ($MediaFolder -eq '') { (Get-Location).Path }
    if ($mediaFolder.substring($mediaFolder.length-1) -ne '\') { $mediaFolder += '\' }        

    if (!(Test-Path -Path .\Functions.ps1))
    {
        Write-Host "Module Functions.ps1 does not exist on the current folder, no futher action taken" -ForegroundColor Red
    }
    else
    {
        Import-Module -name .\Functions.ps1
    }

    $scriptName = ($MyInvocation.MyCommand.Name)
    $StrDateTime = Get-Date -uformat "%d%m%Y-%H%M"
    $path = $MediaFolder + "_Logs\" + ($MyInvocation.MyCommand.Name -replace '.ps1', '') + ".log"
    $component = ($MyInvocation.MyCommand.Name -replace '.ps1', '')
    New-Item ($MediaFolder + '_Logs') -type directory -force | out-null 
    try
    {
        New-Item ($MediaFolder + '_Logs\Test.log') -type file -force | out-null 
        Remove-Item ($MediaFolder + '_Logs\Test.log') -force | out-null 
    }
    catch
    {
        Write-Host "Unable to read/write file on $MediaFolder folder, no futher action taken" -ForegroundColor Red
        Exit    
    }

    [Environment]::SetEnvironmentVariable("SEE_MASK_NOZONECHECKS", "1", "Process")

    if (!(Test-IsAdmin)) { Exit }
    if (!(Test-PowerShell64)) { Exit }
    if (!(Test-PowerShell3)) { Exit }
    if (!(Test-IsMediaFolderExist -MediaFolder $MediaFolder)) { Exit }

    $logsize = 10
    $computerinfo = Get-WmiObject Win32_ComputerSystem
    $computerfqdn = $computerinfo.name + '.' + $computerinfo.Domain

    if (!(Test-IsValidWindowsVersion)) { Exit }
    if (!(Test-IsEnoughDiskSpace -Drive 'C' -DiskSpace 10)) { Exit }

    $siteinstallationtype = (BuildAnswer -return $siteinstallationtype -Question "Site Installation Type?" -options "1=central/2=primary standard/3=primary child/4=secondary" -default "2").ToLower()
    $centralsite = (iif -question ($siteinstallationtype -eq '1') 'y' -falsevalue 'n')
    $primarysitestd = (iif -question ($siteinstallationtype -eq '2') 'y' -falsevalue 'n')
    $primarysitechild = (iif -question ($siteinstallationtype -eq '3') 'y' -falsevalue 'n')
    $secondary = (iif -question ($siteinstallationtype -eq '4') 'y' -falsevalue 'n')
    
    if (($centralsite -eq 'y') -or ($primarysitestd -eq 'y'))
    { $sccmadminsgroup = (Test-ADGroup -groupname $sccmadminsgroup -question "Enter the SCCM Admins AD Security Group" -default "SCCM Admins") }

    if ($secondary -eq 'y')
    { if (!(Test-IsEnoughMemory -MemorySize 2)) { Exit } }
    else { if (!(Test-IsEnoughMemory -MemorySize 4)) { Exit } }

    $sdkServer = (BuildAnswer -return $sdkServer -Question "SDKServer" -default $computerfqdn)
    $sitecode = (BuildAnswer -return $sitecode -Question "Site Code" -allowblank $false -errorMsg 'Site Code')
    if ($sitecode.length -ne 3)
    {
        Write-Log -Message "Site Code must be 3 characters long, no futher action taken" -severity 3
        Exit    
    }
    $sitename = (BuildAnswer -return $sitename -Question "Site Name" -allowblank $false -errorMsg 'Site Name')

    if ($primarysitechild -eq 'y')
    {
        $ParentSiteServer = (BuildAnswer -return $ParentSiteServer -Question "Parent Site Server FQDN Name" -allowblank $false -errorMsg 'Parent Site Server FQDN Name')
    }

    if ($secondary -eq 'y')
    {
        $localdatabase = 'y'
        $sqlserver = $computerfqdn
        $changeDatabase = 'y'
        $InitialSize = '5'
        $NumberOfFiles = 1
        $SecondaryServerNetbiosName = (BuildAnswer -return $SecondaryServerNetbiosName -Question "Secondary Server Netbios Name:" -allowblank $false -errorMsg 'Secondary Server Netbios Name')
        $ParentSiteServer = (BuildAnswer -return $ParentSiteServer -Question "Parent Site Server FQDN Name:" -allowblank $false -errorMsg 'Parent Site Server FQDN Name')
        $ParentSiteCode = (BuildAnswer -return $ParentSiteCode -Question "Parent Site Code:" -allowblank $false -errorMsg 'Parent Site Code')
    }    
    else
    {
        $localdatabase = (BuildAnswer -return $localdatabase -question 'Installing with a Local Database?' -options "y/n" -default "y").ToLower()
        if ($localdatabase -eq 'n')
        { $sqlserver = (BuildAnswer -return $sqlserver -question "Remote Database Server FQDN Name and Instance (servername\instance)" -allowblank $false -errorMsg 'Remote Database Server FQDN Name and Instance') }
        else
        { $sqlserver = $computerfqdn }

        $changeDatabase = (BuildAnswer -return $changeDatabase -question 'Change Database Initial Size and Number of Files?' -options "y/n" -default "n").ToLower()
        if ($changeDatabase -eq 'y')
        {
            $InitialSize = (BuildAnswer -return $InitialSize -question "Database Initial Size (GB)" -allowblank $false -errorMsg 'Database Initial Size')
            $NumberOfFiles = (BuildAnswer -return $NumberOfFiles -question "Number of Database Files" -allowblank $false -errorMsg 'Number of Database Files')
        }
    }

    if (($primarysitestd -eq 'y') -or ($primarysitechild -eq 'y'))
    {
        $useclientpush = (BuildAnswer -return $useclientpush -question "Use client push account" -options "y/n" -default "y").ToLower()
        if ($useclientpush -eq 'y')
        {
            $return = Get-UserNamePassword -username $ClientPushAccount -password $ClientPushAccountPassword -question "Enter the Client Push Account" -errorMsg 'Client Push Account'  -testaccount $true
            $ClientPushAccount = $return[0]
            $ClientPushAccountPassword = $return[1]
    		if ($ClientPushAccount.indexof('\') -lt 0) { $ClientPushAccount = $env:USERDOMAIN + "\" + $ClientPushAccount }
        }
        
        $usenetworkaccessaccount = (BuildAnswer -return $usenetworkaccessaccount -question "Use network access account" -options "y/n" -default "y").ToLower()
        if ($usenetworkaccessaccount -eq 'y')
        {
            $return = Get-UserNamePassword -username $NetworkAccessAccount -password $NetworkAccessAccountPassword -question "Enter the Network Access Account" -errorMsg 'Network Access Account'  -testaccount $true
            $NetworkAccessAccount = $return[0]
            $NetworkAccessAccountPassword = $return[1]
    		if ($NetworkAccessAccount.indexof('\') -lt 0) { $NetworkAccessAccount = $env:USERDOMAIN + "\" + $NetworkAccessAccount }
        }    
    }

    if ($secondary -eq 'n')
    {
        $createServerBoundary = (BuildAnswer -return $createServerBoundary -question 'Create Site Server Boundary/Boundary Group?' -options "y/n" -default "n").ToLower()
    }

    if (($centralsite -eq 'y') -or ($primarysitestd -eq 'y'))
    {
        $forestdiscovery = (BuildAnswer -return $forestdiscovery -question 'Enable forest discovery?' -options "y/n" -default "n").ToLower()
    }

    if (($primarysitestd -eq 'y') -or ($primarysitechild -eq 'y'))
    {
        $systemdiscovery = (BuildAnswer -return $systemdiscovery -question 'Enable System Discovery?' -options "y/n" -default "n").ToLower()
        $userdiscovery = (BuildAnswer -return $userdiscovery -question 'Enable User Discovery?' -options "y/n" -default "n").ToLower()
        $groupdiscovery = (BuildAnswer -return $groupdiscovery -question 'Enable Security Group Discovery?' -options "y/n" -default "n").ToLower()
    } 

    Write-Log -Message "MediaFolder: $MediaFolder"
    Write-Log -Message "CentralSite: $centralsite"
    Write-Log -Message "primarysitestd: $primarysitestd"
    Write-Log -Message "primarysitechild: $primarysitechild"
    Write-Log -Message "secondarysite: $secondary"
    Write-Log -Message "SecondaryServerNetbiosName: $SecondaryServerNetbiosName"
    Write-Log -Message "ParentSiteServer: $ParentSiteServer" 
    Write-Log -message "ParentSiteCode: $ParentSiteCode"
    Write-Log -Message "localdatabase: $localdatabase"
    Write-Log -Message "sqlserver: $sqlserver"
    Write-Log -Message "sdkServer: $sdkServer"
    Write-Log -Message "sitecode: $sitecode"
    Write-Log -Message "sitename: $sitename"
    Write-Log -Message "changeDatabase: $changeDatabase"
    Write-Log -Message "InitialSize: $InitialSize"
    Write-Log -Message "NumberOfFiles: $NumberOfFiles"
    Write-Log -Message "useclientpush: $useclientpush"
    Write-Log -Message "ClientPushAccount: $ClientPushAccount"
    Write-Log -Message "ClientPushAccountPassword: *****"
    Write-Log -Message "usenetworkaccessaccount: $usenetworkaccessaccount"
    Write-Log -Message "NetworkAccessAccount: $NetworkAccessAccount"
    Write-Log -Message "NetworkAccessAccountPassword: *****"
    Write-Log -Message "createServerBoundary: $createServerBoundary"
    Write-Log -Message "forestdiscovery: $forestdiscovery"
    Write-Log -Message "systemdiscovery: $systemdiscovery"
    Write-Log -Message "userdiscovery: $userdiscovery"
    Write-Log -Message "groupdiscovery: $groupdiscovery"

    $inifile = @"
[Identification]
Action=@@ACTION@@

[Options]
ProductID=EVAL
SiteCode=@@SITECODE@@
SiteName=@@SITENAME@@
SMSInstallDir=D:\Program Files\Microsoft Configuration Manager
SDKServer=@@SDKSERVER@@
@@ROLE@@
@@CLIENTPKI@@
PrerequisiteComp=1
PrerequisitePath=@@PREREQ@@
MobileDeviceLanguage=0
AdminConsole=1
JoinCEIP=0

[SQLConfigOptions]
SQLServerName=@@SQLSERVER@@
DatabaseName=CM_@@SITECODE@@
SQLSSBPort=4022

@@HIERARCHYEXPANSIONOPTION@@
@@PARENT@@

"@

    $inicontent = $inifile
    $inicontent = $inicontent -replace "@@SITECODE@@", $SiteCode -replace "@@SITENAME@@", $siteName
    $inicontent = $inicontent -replace "@@SDKSERVER@@", $sdkServer -replace "@@PREREQ@@", ($mediaFolder + 'ConfigMgr2012\SP1\SMSSETUP\Redist')
    $inicontent = $inicontent -replace "@@SQLSERVER@@", $sqlserver

    if ($secondary -eq 'n')
    {
        if ($centralsite -eq 'y')
        {
            $inicontent = $inicontent -replace "@@ACTION@@", 'InstallCAS'
            $inicontent = $inicontent -replace "@@ROLE@@", ''
            $inicontent = $inicontent -replace "@@CLIENTPKI@@", ''
            $inicontent = $inicontent -replace "@@HIERARCHYEXPANSIONOPTION@@", ''
            $inicontent = $inicontent -replace "@@PARENT@@", ''
        }
        elseif ($primarysitestd -eq 'y')
        {
            $inicontent = $inicontent -replace "@@ACTION@@", 'InstallPrimarySite'
            $inicontent = $inicontent -replace "@@ROLE@@", 'RoleCommunicationProtocol=HTTPorHTTPS'
            $inicontent = $inicontent -replace "@@CLIENTPKI@@", 'ClientsUsePKICertificate=0'

            $inicontent = $inicontent -replace "@@HIERARCHYEXPANSIONOPTION@@", ''
            $inicontent = $inicontent -replace "@@PARENT@@", ''
        }
        elseif ($primarysitechild -eq 'y')
        {
            $inicontent = $inicontent -replace "@@ACTION@@", 'InstallPrimarySite'
            $inicontent = $inicontent -replace "@@ROLE@@", 'RoleCommunicationProtocol=HTTPorHTTPS'
            $inicontent = $inicontent -replace "@@CLIENTPKI@@", 'ClientsUsePKICertificate=0'
            $inicontent = $inicontent -replace "@@HIERARCHYEXPANSIONOPTION@@", '[HierarchyExpansionOption]'
            $inicontent = $inicontent -replace "@@PARENT@@", ('CCARSiteServer='+$ParentSiteServer)
        }
	else
	{
            $inicontent = $inicontent -replace "@@HIERARCHYEXPANSIONOPTION@@", ''
            $inicontent = $inicontent -replace "@@PARENT@@", ''
	}
        $inicontent | Out-File -FilePath ($MediaFolder + '_Logs\installcm12.ini')

        Write-Log -Message "ConfigMgr 2012 SP1...Installing" 
        Run-CommandLine -commandline ($MediaFolder + "ConfigMgr2012\SP1\SMSSETUP\BIN\X64\setup.exe") -parameters ("/script " + $MediaFolder + "_Logs\installcm12.ini")
        Write-Log -Message "ConfigMgr 2012 SP1...Done" 
    }

    if ($secondary -eq 'n')
    {
        Write-Log -Message ('Creating Desktop Shortcut...Starting')
        $cm12Console = "$env:ALLUSERSPROFILE\Microsoft\Windows\Start Menu\Programs\Microsoft System Center 2012\Configuration Manager\Configuration Manager Console.lnk"
        if (Test-Path -Path $cm12Console)
        { Copy-Item $cm12Console "$env:USERPROFILE\Desktop" -Force -ErrorAction SilentlyContinue }
        Write-Log -Message ('Creating Desktop Shortcut...Done')
        
        Write-Log -Message ('Configuring Console to Launch SQL Reporting Builder 3...Starting')
        $registry = Get-Item "hklm:software\wow6432node\Microsoft\ConfigMgr10\AdminUI\Reporting" -ErrorAction SilentlyContinue
        if ($registry -ne $null)
        { Set-ItemProperty -Path "hklm:software\wow6432node\Microsoft\ConfigMgr10\AdminUI\Reporting" -Name "ReportBuilderApplication-ManifestName" -Value "ReportBuilder_3_0_0_0.application" | Out-Null }
        Write-Log -Message ('Configuring Console to Launch SQL Reporting Builder 3...Done')
    }

    Write-Log -Message "Sleeping for 60 seconds" 
    Start-Sleep -s 60

    if ($secondary -eq 'n')
    {
        MDTInstallation -mediafolder $MediaFolder
        MDTIntegration

        if (($centralsite -eq 'y') -or ($primarysitestd -eq 'y'))
        { MDTSiteServerIntegration -mediafolder $MediaFolder -sitecode $SiteCode -sdkserver $sdkserver }
    }
    
    if ($primarysitechild -eq 'y')
    {
        Write-Log -Message "Replication from the Parent can take long time. Please, be patient" -severity 2
        while ($true)
        {
            $component = gwmi -Namespace ("root\sms\site_" + $siteCode) -ComputerName ($sdkServer) -query "select * from SMS_Site where SiteCode = '$siteCode'"
            if ($component.Mode -ne 0)
            { 
                Write-Log -Message "Replication from the Parent is still happening. Site in Read-only mode. Please, be patient" -severity 2
                Write-Log -Message "Sleeping for 60 seconds" 
                Start-Sleep -s 60
            }
            else 
            { 
                Write-Log -Message "Replication from the Parent completed"
                break 
            }
        }
    }
    elseif ($secondary -eq 'n')
    {
        Write-Log -Message "Sleeping for 120 seconds" 
        Start-Sleep -s 120
    }
    
    Write-Log -Message "Site validation can take long time. Please, be patient" 
    Write-Log -Message "Sleeping for 120 seconds" 
    Start-Sleep -s 120

    ValidateComponentInstallation -sitecode $siteCode -sdkserver $sdkserver -ComponentName 'SMS_SITE_COMPONENT_MANAGER' -MsgID '1027' -maxretry $maxretry | Out-Null
    ValidateComponentInstallation -sitecode $siteCode -sdkserver $sdkserver -ComponentName 'SMS_HIERARCHY_MANAGER' -MsgID '3306' -maxretry $maxretry | Out-Null
    
    Write-Log -Message "Sleeping for 120 seconds" 
    Start-Sleep -s 120
   
    $component = ValidateComponentInstallation -sitecode $siteCode -sdkserver $sdkserver -ComponentName 'SMS_WINNT_SERVER_DISCOVERY_AGENT' -MsgID '4202' -maxretry $maxretry
    if ($component -ne $null)
    {
        $total = $component.InsStrValue
        $component = gwmi -Namespace ("root\sms\site_" + $siteCode) -ComputerName ($sdkServer) -query "select * from SMS_SCI_SysResUse where FileType = 2 and SiteCode = '$SiteCode'"
        if (([int]$component.Count) -ne ([int]$total))
        { Write-Log -Message ('The number of Site Systems Created does not match the number that should be created') -severity 3 }
        else { Write-Log -Message ('The number of Site Systems Created match the number that should be created') }
    }    

    if ($primarysitechild -eq 'y')
    { 
        Write-Log -Message "Sleeping for 120 seconds" 
        Start-Sleep -s 120
        ValidateComponentInstallation -sitecode $siteCode -sdkserver $sdkserver -Component 'SMS_REPLICATION_CONFIGURATION_MONITOR' -MsgID '7828' -maxretry ($maxretry*2) | Out-Null 
    }

    Test-IsSitePublishedAD -sitecode $SiteCode
    if (($centralsite -eq 'y') -or ($primarysitestd -eq 'y'))
    { AddFullAdminUserToSCCM -sdkserver $sdkServer -sitecode $SiteCode -name $sccmadminsgroup -adduser $false }

    Write-Log -Message ('Log size...Configuring it to '+$logsize+' MB') 
    Get-ChildItem "hklm:Software\Microsoft\SMS\Tracing" | ForEach-Object { (set-ItemProperty -path $_.psPath -name 'MaxFileSize' -value ($logsize*1024*1024)) }
    Write-Log -Message ('Log size...Done')

    Write-Log -Message ('Backup Folder...Creating') 
    New-Item 'e:\SCCMBackup' -Force -type directory | Out-Null
    Write-Log -Message ('Backup Folder...Done') 

    if (($primarysitestd -eq 'y') -or ($primarysitechild -eq 'y'))
    {
        Set-MaintenanceTask -TaskName 'Delete Obsolete Client Discovery Data' -Enabled $true -sitecode $siteCode -sdkserver $sdkserver
        Set-MaintenanceTask -TaskName 'Delete Inactive Client Discovery Data' -Enabled $true -sitecode $siteCode -sdkserver $sdkserver
        Set-MaintenanceTask -TaskName 'Evaluate Provisioned AMT Computer Certificates' -Enabled $false -sitecode $siteCode -sdkserver $sdkserver
        Set-MaintenanceTask -TaskName 'Delete Aged Replication Summary Data' -Enabled $true -Days 60 -sitecode $siteCode -sdkserver $sdkserver
    }

    Set-MaintenanceTask -TaskName 'Rebuild Indexes' -Enabled $true -sitecode $siteCode -sdkserver $sdkServer
    Set-MaintenanceTask -TaskName 'Backup SMS Site Server' -Enabled $true -sitecode $siteCode -sdkserver $sdkServer

    if (($primarysitestd -eq 'y') -or ($primarysitechild -eq 'y'))
    {
        if ($ClientPushAccount -ne '')
        {
            CreateSCCMAccount -sdkserver $sdkserver -sitecode $sitecode -username $ClientPushAccount -password $ClientPushAccountPassword
            
            Write-Log -Message ('Adding Client Push Information...Starting')
    		ChangePropListComponent -sdkserver $sdkserver -sitecode $sitecode -property 'Reserved2' -Value $ClientPushAccount -componentname ('SMS_CLIENT_CONFIG_MANAGER|' + $sdkServer)
            Write-Log -Message ('Adding Client Push Information...Done')
        }
        
        if ($NetworkAccessAccount -ne '')
        {
            CreateSCCMAccount -sdkserver $sdkserver -sitecode $sitecode -username $NetworkAccessAccount -password $NetworkAccessAccountPassword
            Write-Log -Message ('Adding Network Access Account Information...Starting')
            ChangePropClientComp -sdkServer $sdkServer -sitecode $siteCode -component 'Software Distribution' -property 'Network Access User Name' -value 0 -value1 "REG_SZ" -value2 $NetworkAccessAccount
            Write-Log -Message ('Adding Network Access Account Information...Done')
        }
    }

    if ($changeDatabase -eq 'y')
    { ChangeDatabaseSize -sdkserver $sdkserver -sitecode $sitecode -InitialSize $InitialSize -NumberOfFiles $NumberOfFiles }

    if (($centralsite -eq 'y') -or ($primarysitestd -eq 'y'))
    {
        if ($createServerBoundary -eq 'y')
        {
            New-BoundaryGroup -sdkServer $sdkServer -sitecode $siteCode -Name ($env:USERDNSDOMAIN)
            $network = gwmi win32_networkadapterconfiguration | where-object { $_.IPAddress -ne $null}
            $boundaryID = New-IPRangeBoundary -sdkServer $sdkServer -sitecode $siteCode -IPAddress ($network.IPAddress[0]) -IPSubnet ($network.IPSubnet[0]) -Description 'Site Server IP Range'
            AssignBoundaryToBoundaryGroup -sdkServer $sdkServer -sitecode $siteCode -BoundaryGroupName ($env:USERDNSDOMAIN) -BoundaryID $boundaryID        
        }
        
        if ($forestdiscovery -eq 'y')
        {
            Write-log -message ('Enabling forest discovery...Starting')
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Enable Subnet Boundary Creation' -value 1 -componentname ('SMS_AD_FOREST_DISCOVERY_MANAGER|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'SETTINGS' -value 0 -value1 'ACTIVE' -componentname ('SMS_AD_FOREST_DISCOVERY_MANAGER|'+$sdkserver)
            ChangeComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Flag' -value 6 -componentname ('SMS_AD_FOREST_DISCOVERY_MANAGER|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Run Count' -value 1 -componentname ('SMS_AD_FOREST_DISCOVERY_MANAGER|'+$sdkserver) -increasebyvalue $true
            Write-log -message ('Enabling forest discovery...Done')
        }
    }

    if (($primarysitestd -eq 'y') -or ($primarysitechild -eq 'y'))
    {
    	$adcontainer = Get-LDAPDomain
    	if ($systemdiscovery -eq 'y')
        {
            Write-log -message ('Enabling system discovery for '+$adcontainer+'...Starting')
            ChangePropListComponent -sdkServer $sdkServer -sitecode $siteCode -property 'AD Containers' -value (@($adcontainer,'0','1')) -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropListComponent -sdkServer $sdkServer -sitecode $siteCode -property 'AD Attributes' -value 'pwdLastSet' -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Enable Filtering Expired Logon' -value 1 -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Enable Filtering Expired Password' -value 1 -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'SETTINGS' -value 0 -value1 'ACTIVE' -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangeComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Flag' -value 6 -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Run Count' -value 1 -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            Write-log -message ('Enabling system discovery for '+$adcontainer+'...Done')
        }
        
        if ($userdiscovery -eq 'y')
        {
            Write-log -message ('Enabling user discovery for '+$adcontainer+'...Starting')
            ChangePropListComponent -sdkServer $sdkServer -sitecode $siteCode -property 'AD Containers' -value (@($adcontainer,'0','1')) -componentname ('SMS_AD_USER_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropListComponent -sdkServer $sdkServer -sitecode $siteCode -property 'AD Attributes' -value 'pwdLastSet' -componentname ('SMS_AD_USER_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'SETTINGS' -value 0 -value1 'ACTIVE' -componentname ('SMS_AD_USER_DISCOVERY_AGENT|'+$sdkserver)
            ChangeComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Flag' -value 6 -componentname ('SMS_AD_USER_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Run Count' -value 1 -componentname ('SMS_AD_USER_DISCOVERY_AGENT|'+$sdkserver)
            Write-log -message ('Enabling user discovery for '+$adcontainer+'...Done')
        }
        
        if ($groupdiscovery -eq 'y')
        {
            Write-log -message ('Enabling Security Group discovery for '+$adcontainer+'...Starting')
            ChangePropListComponent -sdkServer $sdkServer -sitecode $siteCode -property ('Search Bases:domain '+($env:USERDNSDOMAIN)) -value (@($adcontainer)) -componentname ('SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropListComponent -sdkServer $sdkServer -sitecode $siteCode -property 'AD Containers' -value (@('domain '+($env:USERDNSDOMAIN)),'0','0','1') -componentname ('SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Enable Filtering Expired Logon' -value 1 -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Enable Filtering Expired Password' -value 1 -componentname ('SMS_AD_SYSTEM_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'SETTINGS' -value 0 -value1 'ACTIVE' -componentname ('SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT|'+$sdkserver)
            ChangeComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Flag' -value 6 -componentname ('SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT|'+$sdkserver)
            ChangePropComponent -sdkServer $sdkServer -sitecode $siteCode -property 'Run Count' -value 1 -componentname ('SMS_AD_SECURITY_GROUP_DISCOVERY_AGENT|'+$sdkserver)
            Write-log -message ('Enabling Security Group discovery for '+$adcontainer+'...Done')
        }    
    }

    if (($centralsite -eq 'y') -or ($primarysitestd -eq 'y'))
    { Set-ExtendConfigurationMofFile -sdkserver $sdkServer -sitecode $siteCode }

    Set-ConfigMgrInstallation -version '0.2'

    [Environment]::SetEnvironmentVariable("SEE_MASK_NOZONECHECKS", "0", "Process")

    Write-Log -Message ('SCCM Site has been installed')
}
finally
{
    $module = Get-Module -name Functions | where-object {$_.ModuleType -eq "Script"}
    if ($module -ne $null) 
    { 
        if ($module.Path.ToLower() -eq ($MediaFolder.ToLower() + "scripts\functions.ps1")) { Remove-Module $module }
    }
} 